package com.itheima.dao;

import com.itheima.domain.Role;
import com.itheima.domain.UserInfo;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

public interface IUserInfoDao {

    /**
     * 查询所有用户信息
     *
     * @return
     */
    @Select("select * from UserInfo")
    List<UserInfo> findAllUserInfo();


    /**
     * 添加新用户信息
     *
     * @param userInfo
     */
    @Select("INSERT INTO USERINFO (ID, EMAIL, USERNAME, PASSWORD, PHONENUM, STATUS) VALUES (SYS_GUID(), #{email}, #{username}, #{password}, #{phoneNum}, #{status})")
    void insertUserInfo(UserInfo userInfo);


    /**
     * 根据id查询用户的详细信息
     *
     * @param UserInfoId 用户id
     * @return
     */
    @Select("select * from userInfo where id = #{UserInfoId}")
    @ResultMap("login")
    UserInfo findByUserInfoId(String UserInfoId);


    /**
     * 登录验证
     *
     * @param username 用户名
     * @return
     */
    @Select("select * from userInfo where username = #{username}")
    @Results(id = "login", value = {
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "email", column = "email"),
            @Result(property = "username", column = "username"),
            @Result(property = "password", column = "password"),
            @Result(property = "phoneNum", column = "phoneNum"),
            @Result(property = "status", column = "status"),
            //查询用户对应的角色信息：一对多
            @Result(property = "roles", column = "id", javaType = List.class,
                    many = @Many(select = "com.itheima.dao.IRoleDao.findRoleByUserInfo", fetchType = FetchType.LAZY))
    })
    UserInfo findByUserInfoUsername(String username);


    /**
     * 根据用户id查询此用户未拥有的角色
     *
     * @param userInfoId 用户ID
     * @return
     */
    @Select("select * from role where id not in(select ROLEID from USERINFO_ROLE where USERID = #{userInfoId})")
    List<Role> insertUserInfoRole(String userInfoId);

    /**
     * 根据用户id和角色id，添加此用户未拥有的角色
     *
     * @param userInfoId 用户ID
     * @param roleId     角色ID
     */
    @Insert("insert into USERINFO_ROLE(USERID,ROLEID) values(#{userInfoId},#{roleId})")
    void insertByUserInfoIdAndRoleId(@Param("userInfoId") String userInfoId, @Param("roleId") String roleId);
}
